package com.lrkj.back.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lrkj.back.Const;
import com.lrkj.back.StartUpOnLoadData;
import com.lrkj.back.service.TbManufactorService;
import com.lrkj.back.service.ZsShenqingYicipinMingxiService;
import com.lrkj.back.service.ZsYicipinKucunService;
import com.lrkj.back.service.ZsYicipinRukuService;
import com.lrkj.back.entity.TbDepartment;
import com.lrkj.back.entity.TbEmployee;
import com.lrkj.back.entity.ZsShenqingYicipinMingxi;
import com.lrkj.back.entity.ZsYicipinRuku;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.lrkj.back.entity.TbManufactor;
import com.lrkj.back.entity.ZsShenqing;
import com.lrkj.back.entity.ZsYicipinKucun;
import com.lrkj.back.entity.ZsYicipinRukumingxi;
import com.lrkj.back.service.TbDepartmentService;
import com.lrkj.back.service.TbSeqService;
import com.lrkj.back.service.ZsShenqingService;
import com.lrkj.back.service.ZsYicipinRukumingxiService;
import cn.com.cbons.mamisay.parent.exception.BusinessException;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping("/oneOff")
public class ZsYicipinController extends BaseController{
	@Autowired
	private ZsYicipinRukuService yicipinService;
	@Autowired
	private ZsYicipinRukumingxiService mingxiService;
	@Autowired
	private ZsYicipinKucunService kucunService;
	@Autowired
	private ZsShenqingService shenqingService;
	@Autowired
	private TbManufactorService manufactorService;
	@Autowired
	private ZsShenqingYicipinMingxiService sqmxService;
	
	@Autowired
	private TbSeqService seqService;
	//配置--一次品档案   （点击查询）
	@RequestMapping("/yicipinStoreList.do")
	public ModelAndView yicipinStoreList(String searchTxt,HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		Integer pageNo = request.getParameter("pageIndex")==null? 1 :Integer.valueOf(request.getParameter("pageIndex"));
		Map<String,Object> map =new HashMap<String,Object>();
		if(StringUtils.isNotBlank(searchTxt)){
			map.put("productName", searchTxt.trim());
		}
		map.put("pageNo", pageNo);
		map.put("pageSize", Const.PAGE_SIZE);
		PageInfo<ZsYicipinKucun> page = kucunService.findAllYicipinKucun(map);
		request.setAttribute("kucunList", page.getList());
		request.setAttribute("searchTxt", searchTxt==null?"":searchTxt);
		request.setAttribute("total", page.getPages());
		return new ModelAndView("/peizhi/yicipindangan/store_list");
	}
	
	@RequestMapping("/yicipinStoreEdit.do")
	public ModelAndView yicipinStoreEdit(String id,HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		ZsYicipinKucun kucun = (id == null) ? new ZsYicipinKucun() : kucunService.selectByPrimaryKey(id);
		request.setAttribute("kucun", kucun);
		List<TbManufactor> gysList = manufactorService.findAllManufactor(new HashMap<String,Object>());
		request.setAttribute("gysList", gysList);
		return new ModelAndView("/peizhi/yicipindangan/store_edit");
	}
	
	@RequestMapping("/yicipinStoreSave.do")
	@ResponseBody
	public Map<Object, Object> yicipinStoreSave(ZsYicipinKucun kucun,HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<>();
		try {
			kucun.setRukuCreatetime(new Date());
			kucun.setProductNum(0);
			if(StringUtils.isNotBlank(kucun.getProductId())){
				kucunService.updateByPrimaryKey(kucun);
			}else{
				SimpleDateFormat sdf= new SimpleDateFormat("yyMMdd");
				String proId = sdf.format(new Date())+seqService.seqVal("ycipinno");
				kucun.setProductId(proId);
				kucunService.insert(kucun);
			}
			rtnMap.put("status", "true");
			rtnMap.put("msg", "编辑成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "编辑失败");
			e.printStackTrace();
		}
		return rtnMap;
	}
	
	@RequestMapping("/yicipinStoreDel.do")
	@ResponseBody
	public Map<Object, Object> yicipinStoreDel(HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<Object,Object>();
		try {
			String ids = request.getParameter("id");
			String[] arraId = ids.split(",");
			for(String tid : arraId){
				kucunService.deleteByPrimaryKey(tid);
			}
			rtnMap.put("status", "true");
			rtnMap.put("msg", "删除成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "删除失败");
			e.printStackTrace();
		}
		return rtnMap;
	}
	
	//配置--一次品入库    （点击查询）
	@RequestMapping("/yicipinList.do")
	public ModelAndView yicipinList(String searchTxt,String tiaojian,String quzhi,HttpServletRequest request,
			HttpServletResponse response)throws BusinessException, ParseException{
		Integer pageNo = request.getParameter("pageIndex")==null? 1 :Integer.valueOf(request.getParameter("pageIndex"));
		Map<String,Object> map =new HashMap<String,Object>();
		Map<String,Object> tiaojianMap =new HashMap<String,Object>();
		String st = request.getParameter("startTime");
        String et = request.getParameter("endTime");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date startTime = null;
        Date endTime = null;
		if(StringUtils.isNotBlank(tiaojian)){
			tiaojianMap.put("tiaojian", tiaojian);
		}
		List<String> varList = new ArrayList<String>();
		List<ZsYicipinRuku> yicipinRukus = yicipinService.findAllYicipinNopage(tiaojianMap);
		if (!yicipinRukus.isEmpty()) {
			for (ZsYicipinRuku zsYicipinRuku : yicipinRukus) {
				if (!varList.contains(zsYicipinRuku.getRukuFapiaohao())) {
					varList.add(zsYicipinRuku.getRukuFapiaohao());
				}
			}
			map.put("rukufapiaoArr",varList);
		}
		if (yicipinRukus.isEmpty()) {
			varList.add("0");
			map.put("rukufapiaoArr",varList);
		}
		if (StringUtils.isNotBlank(st)) {
        	startTime = sdf.parse(st);
        	map.put("startTime",startTime);
		}
        if (StringUtils.isNotBlank(et)) {
        	endTime = sdf.parse(et);
        	map.put("endTime", endTime);
		}
		map.put("pageNo", pageNo);
		map.put("pageSize", Const.PAGE_SIZE);
		PageInfo<ZsYicipinRuku> page = yicipinService.findAllYicipin(map);
		request.setAttribute("yicipinList", page.getList());
		request.setAttribute("empMap", StartUpOnLoadData.emMap);
		request.setAttribute("searchTxt", searchTxt==null?"":searchTxt);
		request.setAttribute("total", page.getPages());
		request.setAttribute("st", startTime);
		request.setAttribute("et", endTime);
		request.setAttribute("tiaojian",tiaojian);
		return new ModelAndView("/peizhi/yicipinruku/oneoff_list");
	}
	
	@RequestMapping("/yicipinDetailList.do")
	@ResponseBody
	public Map<Object, Object> yicipinDetailList(String id,HttpServletRequest request, HttpServletResponse response)throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<Object,Object>();
		try {
			Map<String,Object> map =new HashMap<String,Object>();
			if(StringUtils.isNotBlank(id)){
				map.put("rukuLiushui", id);
			}
			List<ZsYicipinRukumingxi> mingxiList = yicipinService.findAllYicipinDetail(map);
			rtnMap.put("mxList", mingxiList);
			rtnMap.put("status", "true");
			rtnMap.put("msg", "编辑成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "编辑失败");
			e.printStackTrace();
		}
		return rtnMap;
	}
	 
	
	@RequestMapping("/yicipinEdit.do")
	public ModelAndView yicipinEdit(String id, HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		ZsYicipinRuku ycpRuku = (id == null) ? new ZsYicipinRuku() : yicipinService.selectByPrimaryKey(id);
		Map<String,Object> map =new HashMap<String,Object>();
		if(StringUtils.isNotBlank(id)){
			map.put("rukuLiushui", id);
		}
		List<ZsYicipinRukumingxi> mingxiList = yicipinService.findAllYicipinDetail(map);
		if(mingxiList == null)
			mingxiList = new ArrayList<ZsYicipinRukumingxi>();
		ycpRuku.setRukuMingxi(mingxiList);
		List<ZsYicipinKucun> proList = kucunService.findYicipinKucun(new HashMap<String,Object>());
		request.setAttribute("proList", proList);
		request.setAttribute("proJson", JSON.toJSON(proList));
		request.setAttribute("ycpRuku", ycpRuku);
		return new ModelAndView("/peizhi/yicipinruku/oneoff_edit");
	}
	
	
	@RequestMapping("/yicipinSave.do")
	@ResponseBody
	public Map<Object, Object> yicipinSave(ZsYicipinRuku yicipin,HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<Object,Object>();
		try {
			Date date = new Date();
			String[] proPc = request.getParameterValues("productPici"); 
			String[] proId = request.getParameterValues("productId");
			String[] proName = request.getParameterValues("productName");
			String[] proNum = request.getParameterValues("productNum");
//			String[] proDays = request.getParameterValues("productYouxiaoqiDays");
			yicipin.setRukuTime(date);
			TbEmployee tbEmployee = (TbEmployee) request.getSession().getAttribute("emp");
			yicipin.setRukuRukurenTiaoma(tbEmployee.getEmployeeNo());
			yicipin.setRukuShenheTiaoma("");
			yicipin.setRukuShenheTime(date);
			SimpleDateFormat sdf= new SimpleDateFormat("yyyyMMdd");
			String rukuliushui = sdf.format(date)+seqService.seqVal("rukuno");
			yicipin.setRukuLiushui(rukuliushui);
			yicipinService.insert(yicipin);
			ZsYicipinRukumingxi mingxi = null;
			ZsYicipinKucun ycpKucun = null;
			Calendar ca = null;
			Date youxiaoqi = null;
			for(int i = 0 ;i<proPc.length;i++){
				mingxi = new ZsYicipinRukumingxi();
				ca = Calendar.getInstance();
				ycpKucun = kucunService.selectByPrimaryKey(proId[i]);
				mingxi.setRukuLiushui(rukuliushui);
				mingxi.setRukuMingxiLiushui(sdf.format(date)+seqService.seqVal("rukumingxino"));
				mingxi.setProductPici(proPc[i]);
				mingxi.setProductId(proId[i]);
				mingxi.setProductName(proName[i]);
				mingxi.setProductNum(Integer.valueOf(proNum[i]));
				ca.add(Calendar.DATE, ycpKucun.getProductYouxiaoqi());// num为增加的天数，可以改变的
				youxiaoqi = ca.getTime();
				mingxi.setProductYouxiaoqi(youxiaoqi);
				mingxi.setProductYouxiaoqiDays(ycpKucun.getProductYouxiaoqi());
				mingxi.setRukuCreatetime(date);
				mingxiService.insert(mingxi);
				//修改库存的数据
				kucunService.updateKucun(proId[i],Integer.valueOf(proNum[i]));
			}
			rtnMap.put("status", "true");
			rtnMap.put("msg", "编辑成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "编辑失败");
			e.printStackTrace();
		}
		return rtnMap;
	}
	
	@RequestMapping("/yicipinDel.do")
	@ResponseBody
	public Map<Object, Object> yicipinDel(HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<Object,Object>();
		try {
			String ids = request.getParameter("id");
			String[] arraId = ids.split(",");
			for(String tid : arraId){
				yicipinService.deleteByPrimaryKey(tid);
				Map<String,Object> map =new HashMap<String,Object>();
				if(StringUtils.isNotBlank(tid)){
					map.put("rukuLiushui", tid);
				}
				List<ZsYicipinRukumingxi> mingxiList = yicipinService.findAllYicipinDetail(map);
				for(ZsYicipinRukumingxi mx:mingxiList) {
					kucunService.updateKucun(mx.getProductId(),-(Integer.valueOf(mx.getProductNum())));
					mingxiService.deleteByPrimaryKey(mx.getRukuMingxiLiushui());
				}
			}
			rtnMap.put("status", "true");
			rtnMap.put("msg", "删除成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "删除失败");
			e.printStackTrace();
		}
		return rtnMap;
	}
	@Autowired
	private TbDepartmentService  tbDepartmentServices;

	//临床科室--一次品申请    （点击查询）
	@RequestMapping("/yicipinApplyList.do")
	public ModelAndView yicipinApplyList(String searchTxt,HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
	
		Integer pageNo = request.getParameter("pageIndex")==null? 1 :Integer.valueOf(request.getParameter("pageIndex"));
		Map<String,Object> map =new HashMap<String,Object>();
		//显示下拉
		List<TbDepartment> keshilist = tbDepartmentServices.findAllDepartment();
		request.setAttribute("keshilist", keshilist);
		//下拉 框选择 查询 准备
		if(StringUtils.isNotBlank(searchTxt)){
			System.out.println("hello word"+searchTxt);
			map.put("shenqingKeshi",searchTxt);
		}
		//只看一次品
		map.put("shenqingFenlei", 1);
		map.put("pageNo", pageNo);
		map.put("pageSize", Const.PAGE_SIZE);
		//把分页信息传过去
		PageInfo<ZsShenqing> page = shenqingService.findAllShenqing(map);
		request.setAttribute("shenqingList", page.getList());
		request.setAttribute("searchTxt", searchTxt==null?"":searchTxt);
		request.setAttribute("total", page.getPages());
		//返回到页面
		return new ModelAndView("/linchuang/yicipinshenqing/apply_list");
	}
	
	@RequestMapping("/yicipinApplyEdit.do")
	public ModelAndView yicipinApplyEdit(String id, HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		ZsShenqing shenqing = (id == null) ? new ZsShenqing() : shenqingService.selectByPrimaryKey(id);
//		Map<String,Object> map =new HashMap<String,Object>();
//		if(StringUtils.isNotBlank(id)){
//			map.put("shenqingKeshi", id);
//		}
//		List<ZsShenqingYicipinMingxi> mingxiList = shenqingservice.findAllShenqingMingxi(map);
//		if(mingxiList == null)
//			mingxiList = new ArrayList<ZsShenqingYicipinMingxi>();
//		shenqing.setMingxiList(mingxiList);
		List<ZsYicipinKucun> proList = kucunService.findYicipinKucun(new HashMap<String,Object>());
		request.setAttribute("proList", proList);
		request.setAttribute("proJson", JSON.toJSON(proList));
		request.setAttribute("shenqing", shenqing);
		return new ModelAndView("/linchuang/yicipinshenqing/apply_edit");
	}
	
	@RequestMapping("/yicipinApplySave.do")
	@ResponseBody
	public Map<Object, Object> yicipinApplySave(HttpServletRequest request, HttpServletResponse response)throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<Object,Object>();
		try {
			String[] proId = request.getParameterValues("productId");
			String[] proName = request.getParameterValues("productName");
			String[] proNum = request.getParameterValues("productNum");
			SimpleDateFormat sdf= new SimpleDateFormat("yyyyMMdd");
			String shenqingliushui = sdf.format(new Date())+seqService.seqVal("shenqingno");
			TbEmployee emp =(TbEmployee)request.getSession().getAttribute("emp");
			ZsShenqing sq = new ZsShenqing();
			sq.setShenqingLiushui(shenqingliushui);
			sq.setRecordTime(new Date());
			sq.setShenqingFenlei(1);
			sq.setShenqingShenqingrenTiaoma(emp.getEmployeeNo());
			sq.setShenqingTime(new Date());
			//加科室 emp.getDepartmentName() 加条码
			sq.setShenqingShenherenTiaoma(emp.getEmployeeNo());
			sq.setShenqingKeshi(emp.getDepartment().getDepartmentId().toString());
			sq.setShenqingShenheZhuangtai(0);
			shenqingService.insert(sq);
			ZsShenqingYicipinMingxi mingxi = null;
			for(int i = 0 ;i<proId.length;i++){
				mingxi = new ZsShenqingYicipinMingxi();
				mingxi.setShenqingLiushui((shenqingliushui));
				mingxi.setShenqingMingxiLiushui(sdf.format(new Date())+seqService.seqVal("shenqingmxno"));
				mingxi.setShenqingYicipinBianhao(proId[i]);
				mingxi.setShenqingYicipinMingcheng(proName[i]);
				mingxi.setShenqingKeshi(emp.getDepartment().getDepartmentName());
				mingxi.setShenqingYicipinShuliang(Integer.valueOf(proNum[i]));
				mingxi.setFafangZhuangtai(0);
				mingxi.setShenqingTime(new Date());
				//加科室
				mingxi.setShenqingKeshi(emp.getDepartmentId()+"");
				sqmxService.insert(mingxi); 
			}
			rtnMap.put("status", "true");
			rtnMap.put("msg", "编辑成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "编辑失败");
			e.printStackTrace();
		}
		return rtnMap;
	}
	
	@RequestMapping("/yicipinApplyDel.do")
	public Map<Object, Object> yicipinApplyDel(HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<Object,Object>();
		try {
			String ids = request.getParameter("id");
			String[] arraId = ids.split(",");
			for(String tid : arraId){
				shenqingService.deleteByPrimaryKey(tid);
				Map<String,Object> map =new HashMap<String,Object>();
				if(StringUtils.isNotBlank(tid)){
					map.put("shenqingLiushui", tid);
				}
				List<ZsShenqingYicipinMingxi> mingxiList = sqmxService.findAllYicipinApplyDetail(map);
				for(ZsShenqingYicipinMingxi mx:mingxiList) {
					sqmxService.deleteByPrimaryKey(mx.getShenqingMingxiLiushui());
				}
			}
			rtnMap.put("status", "true");
			rtnMap.put("msg", "删除成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "删除失败");
			e.printStackTrace();
		}
		return rtnMap;
	}
	
	
	@RequestMapping("/yicipinApplyDetailList.do")
	@ResponseBody
	public Map<Object, Object> yicipinApplyDetailList(String id,HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<Object,Object>();
		try {
			Map<String,Object> map =new HashMap<String,Object>();
			if(StringUtils.isNotBlank(id)){
				map.put("shenqingLiushui", id);
			}
			List<ZsShenqingYicipinMingxi> mingxiList = sqmxService.findAllYicipinApplyDetail(map);
			rtnMap.put("mxList", mingxiList);
			rtnMap.put("status", "true");
			rtnMap.put("msg", "编辑成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "编辑失败");
			e.printStackTrace();
		}
		return rtnMap;
	}
	
}
